package com.lagou.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lagou.common.Const;
import com.lagou.common.ServerResponse;
import com.lagou.mapper.UserMapper;
import com.lagou.model.User;
import com.lagou.service.IuserService;
import com.lagou.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("iUserService")
public class UserServiceImpl implements IuserService {
    @Autowired
    private UserMapper mapper;


    @Override
    public ServerResponse<User> login(String username, String password) {
        //检查用户名是否存在
        int resultCount = mapper.checkUserName(username);
        if (resultCount == 0) return ServerResponse.createByErrorMessage("用户不存在");
        //存在，使用MD5给密码加密
        String md5Password = MD5Util.MD5EncodeUtf8(password);
        //登录验证，调用mapper方法，返回一个user对象
        User user = mapper.selectLogin(username, md5Password);
        //如果user对象为空则失败，密码错误
        if (user == null) return ServerResponse.createByErrorMessage("密码错误");

        //登录成功，清空密码，封装ServerResponse，返回成功信息
        user.setPassword(StringUtils.EMPTY);

        return ServerResponse.createBySuccessMessage("登录成功");
    }

    @Override
    public ServerResponse<PageInfo> getUsers(Integer pageNum, Integer pageSize) {
        // 设置分页助手
        PageHelper.startPage(pageNum, pageSize);

        //查询所有用户信息
        List<User> list = mapper.userList();

        //创建pageInfo，把查询到的用户list放到pageInfo中
        PageInfo<User> pageInfo = new PageInfo<>(list);

        //返回serverResponse，添加PageInfo

        return ServerResponse.createBySuccessData(pageInfo);
    }

    @Override
    public ServerResponse<String> add(User user) {
        // 校验用户名
        ServerResponse<String> validResponse = checkValid(user.getUsername(), Const.USERNAME);
        if (!validResponse.isSuccess()) return validResponse;
        //校验邮箱
        validResponse = checkValid(user.getEmail(), Const.EMAIL);
        if (!validResponse.isSuccess()) return validResponse;

        //密码加密
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));

        //添加入库
        int resultCount = mapper.insert(user);
        if (resultCount == 0) return ServerResponse.createByErrorMessage("添加失败");
        return ServerResponse.createBySuccessMessage("添加成功");
    }


    public ServerResponse<String> checkValid(String str, String type) {
        if (StringUtils.isNotBlank(type)) {
            //校验用户名
            if (type.equals(Const.USERNAME)) {
                //查询用户名是否存在
                int count = mapper.checkUserName(str);
                //已存在，返回错误消息：用户名已经存在
                if (count > 0) return ServerResponse.createByErrorMessage("用户名已经存在");
            }
            if (type.equals(Const.EMAIL)) {
                //查询用户名是否存在
                int count = mapper.checkEmail(str);
                //已存在，返回错误消息：用户名已经存在
                if (count > 0) return ServerResponse.createByErrorMessage("邮箱已经存在");
            }
        }
        return ServerResponse.createBySuccessMessage("校验成功");
    }
    /**
     *
     * @param id
     * @return
     */
    @Override
    public ServerResponse<String> deleteByPrimary(int id) {
        //判断用户是否存在
        //不存在返回失败的Response
        //存在则进行删除，得到返回值 count==1 删除成功 ==0 删除失败
        return null;
    }

    @Override
    public ServerResponse<String> edit(User user) {

        User old_user = mapper.selectById(user.getId());
        if (null == old_user){old_user=new User();}
        //判断用户名是否与其他用户重复
        int re = mapper.checkUserName(user.getUsername());
        if( re>0 && !old_user.getUsername().equals(user.getUsername())) {
            return ServerResponse.createByErrorMessage("用户名已存在");
        }
        //判断邮箱是否与其他用户重复
        re = mapper.checkEmail(user.getEmail());
        if (re>0 && !old_user.getEmail().equals(user.getEmail())) {
            return ServerResponse.createByErrorMessage("邮箱已存在");
        }
        //修改入库
        re = mapper.updateUser(user);//re为受到影响的行数
        return re>0?ServerResponse.createBySuccessMessage("数据添加成功")
                :ServerResponse.createByErrorMessage("数据修改失败");
    }

    @Override
    public ServerResponse<User> findById(int id) {
        User user = mapper.selectById(id);
        return (null!=user)?ServerResponse.createBySuccessData(user):ServerResponse.createByError();
    }
}
